package com.unis.service.es.impl;

import com.unis.common.annotation.ESField;
import com.unis.common.listener.MyApplicationListener;
import com.unis.service.es.EsService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;

@Service("esService")
public class EsServiceImpl implements EsService {
    final Logger log = LoggerFactory.getLogger(EsServiceImpl.class);
    @Autowired
    TransportClient transportClient;


    @Override
    public SearchResponse getEsData(String tab, String gjz, int page) {
        Class esClass = MyApplicationListener.esClassCache.get(tab);
        String[] dc = gjz.split(":");
        String keyword = "";
        if (dc.length == 2) {
            keyword = dc[0].trim();
            gjz = dc[1].trim();
        }
        // 构造查询请求
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        for (Field field : esClass.getDeclaredFields()) {
            field.setAccessible(true);
            if (field.isAnnotationPresent(ESField.class)) {
                ESField eSField = field.getAnnotation(ESField.class);
                if (StringUtils.isNotBlank(keyword)) {
                    if (eSField.text().contains(keyword)) {
                        String name = (StringUtils.isNotBlank(eSField.name())) ? eSField.name() : field.getName();
                        boolQueryBuilder.should(QueryBuilders.wildcardQuery(name + ".keyword", "*" + gjz + "*"));
                    }
                } else {
                    String name = (StringUtils.isNotBlank(eSField.name())) ? eSField.name() : field.getName();
                    boolQueryBuilder.should(QueryBuilders.wildcardQuery(name + ".keyword", "*" + gjz + "*"));
                }
            }
        }
        if (boolQueryBuilder.should().size() == 0) {
            boolQueryBuilder.should(QueryBuilders.wildcardQuery(".keyword", "*" + gjz + "*"));

        }
        SearchRequestBuilder searchRequest = transportClient.prepareSearch(tab).setTypes("doc");
        searchRequest.setQuery(boolQueryBuilder);
        if (page == -1) {
            searchRequest.setFrom(0).setSize(0);
        } else {
            searchRequest.setFrom((page - 1) * 10).setSize(10);
        }

        SearchResponse response = null;
        try {
            response = searchRequest.execute().actionGet();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}
